package com.applink.sell_proof.fragment;

import java.util.List;
import java.util.Observable;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.applink.sell_proof.R;
import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.builder.AbstractListBuilder;
import com.applink.sell_proof.builder.AllClaimBuilder;
import com.applink.sell_proof.constant.Constant;

public class SearchClaim extends SearchProject {

	private AbstractListBuilder mSeachBuilder;

	private String mKey;
	private String mValue;

	public static final String TAG = "SEARCH_CLAIM";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		if (mView == null)
			mView = (ViewGroup) inflater.inflate(R.layout.listview_white_bg,
					null, false);

		if (mSeachBuilder == null)
			mSeachBuilder = new AllClaimBuilder(getActivity(),
					(ViewGroup) mView.findViewById(android.R.id.list));

		return mView;
	}

	@Override
	public void onPause() {
		super.onPause();
		DataHelper.getInstance().deleteObserver(this);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();

		if (mView != null) {
			ViewGroup parentViewGroup = (ViewGroup) mView.getParent();
			if (null != parentViewGroup) {
				parentViewGroup.removeView(mView);
			}
		}
	}

	public void searchDeal(String key, String value, Context c) {

		if (mSeachBuilder != null)
			mSeachBuilder.clear();
		else {

			if (mView == null) {
				LayoutInflater inflater = (LayoutInflater) c
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

				mView = (ViewGroup) inflater.inflate(
						R.layout.listview_white_bg, null, false);
			}

			mSeachBuilder = new AllClaimBuilder(c,
					(ViewGroup) mView.findViewById(android.R.id.list));
		}

		mKey = key;
		mValue = value;

		DataHelper.getInstance().addObserver(this);

		if (mKey.equals(Constant.KEY_SEARCH_DEAL_BY_NAME))
			DataHelper.getInstance().searchClaim(mValue);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void update(Observable observerable, Object data) {

		if (data == null)
			return;

		DataResult result = (DataResult) data;
		if (result.getMethodName() == Methods.searchClaim) {

			if (mSeachBuilder != null)
				mSeachBuilder.clear();

			mSeachBuilder.setData((List<? extends Object>) result.getData());
		}
	}
}
